<?php

namespace backend\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\helpers\Html;
use yii\helpers\Url;
use yii\helpers\VarDumper;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "admin".
 *
 * @property integer $id
 * @property string $username
 * @property string $auth_key
 * @property string $auth_key_create_time
 * @property string $password_hash
 * @property string $password_reset_token
 * @property integer $status
 * @property string $email
 * @property string $salt
 * @property integer $created_at
 * @property integer $updated_at
 * @property integer $last_login_time
 * @property string $last_login_ip
 */
class Admin extends ActiveRecord implements IdentityInterface
{

    const STATUS_DELETE = 0;

    const STATUS_ACTIVE= 10;

    public $newPassword;

    public $password_reset;

    public $userRoles;


    public static $StatusValue =[10=>'正常',1=>'恢复的管理员',0=>'已经删除'];

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'admin';
    }

    /**
     * 附加行为 系统的行为
     * @return array
     */
    /*public function behaviors()
    {
        return [
            'class'=>TimestampBehavior::className(),
        ];
    }*/

    /**
     * 附加行为 系统的行为
     * @return array
     */
    public function behaviors()
    {
        return [
            //给行为命名
            'time'=>[
                //一个行为一个数组
                'class'=>TimestampBehavior::className(),
                'attributes'=>[
                    //插入之前执行的事件
                    ActiveRecord::EVENT_BEFORE_INSERT=>['created_at','updated_at'],
                    //更新之前执行的事件
                    ActiveRecord::EVENT_BEFORE_UPDATE=>['updated_at'],
                ],


            ],
        ];
    }
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'auth_key', 'password_hash', 'email', 'salt', 'updated_at'], 'required'],
            [['auth_key_create_time', 'status', 'created_at', 'updated_at', 'last_login_time'], 'integer'],
            [['username', 'password_hash', 'password_reset_token', 'email'], 'string', 'max' => 255],
            [['auth_key'], 'string', 'max' => 32],
            [['salt'], 'string', 'max' => 64],
            [['last_login_ip'], 'string', 'max' => 15],
            [['username'], 'unique'],
            [['email'], 'unique'],
            [['userRoles'], 'safe'],
            [['password_reset_token'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => '用户名',
            'auth_key' => '自动登录令牌',
            'auth_key_create_time' => '令牌创建时间',
            'password_hash' => '密码',
            'password_reset_token' => 'Password Reset Token',
            'status' => '状态',
            'email' => '邮箱',
            'salt' => '盐',
            'created_at' => '注册时间',
            'updated_at' => 'Updated At',
            'last_login_time' => '最后登录时间',
            'last_login_ip' => '最后登录ip',
            'password_reset'=>'密码重置令牌(如果修改密码必填)',
            'newPassword'=>'新密码',
            'userRoles'=>'角色',
        ];
    }


    /**
     * 加密密码得到hash密码
     * @param $password '需要加密的密码'
     */
    public function setPassword($password){
        $this->password_hash = \Yii::$app->security->generatePasswordHash($password,$this->salt);
    }

    /**
     *  生成验证令牌
     */
    public function generateAuthKey(){
        //生成32位的验证令牌字符串
        $this->auth_key = \Yii::$app->security->generateRandomString();
        //保存令牌的生成时间
        $this->auth_key_create_time = time();
    }

    /**
     * @param $string '生成密码重置token'
     */
    public function setPasswordResetToken($string)
    {
        $this->password_reset_token = \Yii::$app->security->generatePasswordHash($string);
    }


    /**
     * $menuItems = [
        ['label' => 'Home', 'url' => ['/site/index']],
        ['label' => '注册&nbsp;'.Html::tag('span',' ',['class'=>'glyphicon glyphicon-user']),
            'url' => ['/manager/signup'],
            'options'=>[
            //可以把属性添加到li标签上
                'title'=>'注册',
             ]
       ],
    ];
     *
     * 'label'=>Html::tag('span',' ',['class'=>'glyphicon glyphicon-th-list']).' &nbsp;内容管理',
    'items'=>[
    //                        '<li class="divider list-group-item"></li>',
    ['label'=>'当前页面','url'=>\yii\helpers\Url::current(),'options'=>['class'=>' list-group-item'],],
    ['label'=>'商标管理','url'=>['brand/index'],'options'=>['class'=>' list-group-item'],],
    ['label'=>'文章分类管理','url'=>['article-category/index'],'options'=>['class'=>' list-group-item'],],
    ['label'=>'文章管理 list-group','url'=>['article/index'],'options'=>['class'=>' list-group-item'],],
    ['label'=>'商品分类管理','url'=>['goods-category/index'],'options'=>['class'=>' list-group-item'],],
    ['label'=>'商品管理','url'=>['goods/index'],'options'=>['class'=>' list-group-item'],],
    ['label'=>'site管理','url'=>['site/index'],'options'=>['class'=>' list-group-item'],],
    ['label'=>'管理员管理','url'=>['manager/index'],'options'=>['class'=>' list-group-item'],],

    ],
     */

    public function generateMenu(){
        /** 生成菜单信息的多维数组 */
        // 获取菜单信息

        $menucontent =[];
        $menus = Menu::find();
        foreach($menus->where(['level'=>1])->all() as $menu){
            $items= [];
            //获取当前菜单的子菜单
            $childen = $menus->where(['parent_id'=>$menu->id])->all();
            //遍历子菜单
            foreach ($childen as $child){
                if(Yii::$app->user->can($child->route)){
                    $items[]= ['label'=>$child->name,'url'=>["$child->route"],'options'=>['class'=>' list-group-item'],];
                }
            }
//            var_dump($childen);exit;
           // if(Yii::$app->user->can($menu->route)){
            if(!empty($items)){
                $menucontent[] =['label' => $menu->name,'items'=>$items ];
            }
            //}
        }
        //VarDumper::dump($menucontent,10,true);exit;
        return $menucontent;



    }
    /**
     * @inheritdoc
     * @return AdminQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new AdminQuery(get_called_class());
    }

    /**
     * Finds an identity by the given ID.
     * @param string|int $id the ID to be looked for
     * @return IdentityInterface the identity object that matches the given ID.
     * Null should be returned if such an identity cannot be found
     * or the identity is not in an active state (disabled, deleted, etc.)
     */
    public static function findIdentity($id)
    {
        return Admin::findOne(['id'=>$id,'status'=>self::STATUS_ACTIVE]);
    }

    /**
     * Finds an identity by the given token.
     * @param mixed $token the token to be looked for
     * @param mixed $type the type of the token. The value of this parameter depends on the implementation.
     * For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be `yii\filters\auth\HttpBearerAuth`.
     * @return IdentityInterface the identity object that matches the given token.
     * Null should be returned if such an identity cannot be found
     * or the identity is not in an active state (disabled, deleted, etc.)
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        return Admin::findOne(['auth_key'=>$token]);
    }

    /**
     * Returns an ID that can uniquely identify a user identity.
     * @return string|int an ID that uniquely identifies a user identity.
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Returns a key that can be used to check the validity of a given identity ID.
     *
     * The key should be unique for each individual user, and should be persistent
     * so that it can be used to check the validity of the user identity.
     *
     * The space of such keys should be big enough to defeat potential identity attacks.
     *
     * This is required if [[User::enableAutoLogin]] is enabled.
     * @return string a key that is used to check the validity of a given identity ID.
     * @see validateAuthKey()
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * Validates the given auth key.
     *
     * This is required if [[User::enableAutoLogin]] is enabled.
     * @param string $authKey the given auth key
     * @return bool whether the given auth key is valid.
     * @see getAuthKey()
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }
}
